﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Data;
using System.Data.SQLite;
using WattsUpComponent;
using System.Threading;
using System.Diagnostics;
using System.ComponentModel;
using Regression1;
using Microsoft.VisualBasic;
using System.Windows.Forms;

//using ConsoleApplication1.PowerDSTableAdapters;



namespace data
{

    public class matrixR
    {

        public int numberOfRows { get; set; }
        public double[,] matrix1 { get; set; }

        public matrixR(int NR, double[,] m2)
        {
            numberOfRows = NR;
            matrix1 = new double[numberOfRows, 2];
            matrix1 = m2;

        }
    }
    class storeInDb
    {
        protected static PerformanceCounter cpuCounter;
        protected static PerformanceCounter ramCounter;

       /* public static DataTable funcFillDataTable(string query)
        {

            SQLiteDataAdapter da = new System.Data.SQLite.SQLiteDataAdapter(query, sql_con);
            DataTable dt = new DataTable();
            try
            {
                dt.BeginLoadData();
                da.Fill(dt);
                dt.EndLoadData();
                return dt;
            }
            catch
                (Exception ex) { MessageBox.Show("The following query failed:\r\n\r\n" + query + "\r\n\r\nbecause " + ex.Message); }
            finally { if (da != null) da.Dispose(); }
            return dt;
        }*/
        public static void cpufunc()
        {
            cpuCounter = new PerformanceCounter();

            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";
        }



        [DllImport("C:\\Mosaic\\work1.dll")]
        private static extern int performFunctions();
        //variable for the connection
        private static SQLiteConnection sql_con;

        public static void SetConnection()
        {
            // open the database
            String connectionString = "data source=" + "C:\\Mosaic\\powerdb" +
          ";Version=3;";
            sql_con = new SQLiteConnection
                (connectionString);
        }



        public static float getCurrentCpuUsage()
        {
            return cpuCounter.NextValue();
        }

        public static void openDatabase()
        {
            SetConnection();
            if (sql_con.State != ConnectionState.Open)
            {
                try
                {

                    sql_con.Open();

                }

                catch (Exception)
                {

                    Console.WriteLine("not open");
                }
            }

        }
        public static void storeCpuPower(float cpuUsage, double powerW)
        {

            SQLiteDataReader queryCommandReader;
            SQLiteCommand cmd = new SQLiteCommand("  SELECT ProcessID, ProcessName FROM Process WHERE  (ProcessName = 'workBench')", sql_con);
                  
            queryCommandReader = cmd.ExecuteReader();
            DataTable dataTable = new DataTable();
            dataTable.Load(queryCommandReader);
            int check = dataTable.Rows.Count;
              
            Int64 id2 = (Int64)dataTable.Rows[0][0];
                
             DateTime currentTime = DateTime.Now;
                
                if (powerW != -1)
                {
                    Console.WriteLine(powerW);
                    string query2 = "  INSERT INTO   taskManager(dataID,Power,cpu,DATE)  values ('" + id2 + "','" + powerW + "','" + cpuUsage + "','" + currentTime + "' )";
                    try
                    {
                        openDatabase();
                        cmd = new SQLiteCommand(query2, sql_con);
                        cmd.ExecuteNonQuery();

                    }
                    catch
                        (Exception ex) { MessageBox.Show("The following query failed:\r\n\r\n" + query2 + "\r\n\r\nbecause " + ex.Message); }
                   
                
            }
        }

        static matrixR storeInMatrix(int id)
        {
            openDatabase();
          //  SQLiteCommand cmd = new SQLiteCommand(" SELECT taskManager.cpu,Power.PowerWatts FROM taskManager, Power WHERE taskManager.time = Power.Time ", sql_con);
            SQLiteCommand cmd = new SQLiteCommand(" SELECT taskManager.cpu,taskManager.power FROM taskManager where taskmanager.dataid =" +id, sql_con);
            SQLiteDataReader queryCommandReader;
            DataTable dataTable;
            queryCommandReader = cmd.ExecuteReader();
            dataTable = new DataTable();
            dataTable.Load(queryCommandReader);
            int numberOfRows1 = dataTable.Rows.Count;//get cpu and power  , and store in dynamic array for the regression to read in
            double[,] matrix = new double[numberOfRows1, 2];
       
            int i = 0;

            foreach (DataRow dr in dataTable.Rows)
            {
                matrix[i, 0] = (double)dr[0];
                matrix[i, 1] = (double)dr[1];
                i++;
            }
            matrixR m = new matrixR(numberOfRows1, matrix);
            return m;
        }

        public static int DisplayProcessStatus(Process process)
        {
            process.Refresh();  // Important


            if (process.HasExited)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }


        static void Main(string[] args)
        {
            openDatabase();
            SQLiteCommand create = new SQLiteCommand("CREATE TABLE IF NOT EXISTS Process(ProcessID integer Primary key, ProcessName varchar(50))", sql_con);
            create.ExecuteNonQuery();
            openDatabase();
            create = new SQLiteCommand("CREATE TABLE IF NOT EXISTS taskManager( DataID int, Power float,CPU float,DATE date current_date DEFAULT CURRENT_DATE, TIME time current_time DEFAULT CURRENT_TIME )", sql_con);
            create.ExecuteNonQuery();
            openDatabase();
            create = new SQLiteCommand("CREATE TABLE IF NOT EXISTS Power( PowerID integer, PowerWatts float, DATE DEFAULT Current_Date ,Time DATETIME DEFAULT Current_Time)", sql_con);
            create.ExecuteNonQuery();
            
           //insert id of process
            SQLiteCommand cmd = new SQLiteCommand("  SELECT ProcessID, ProcessName FROM Process WHERE  (ProcessName = 'workbBench')", sql_con);

            // Use the above SqlCommand object to create a SqlDataReader object.
            SQLiteDataReader queryCommandReader;
            DataTable dataTable;
            queryCommandReader = cmd.ExecuteReader();
            if (queryCommandReader.HasRows == false)
            {
                openDatabase();
                cmd = new SQLiteCommand("insert into Process (ProcessName) values ('workBench')", sql_con);
                cmd.ExecuteNonQuery();
               
                Console.WriteLine("Stored");
               }
            Process workbench = Process.Start("C:\\Mosaic\\CPU_WORKLOAD_GENERATOR.exe");
           Thread.Sleep(2000);

            //string currentTime = DateTime.Now.ToString("HH:MM:SS" );
            int count = 0;
            cpufunc();

            while (true)
            {
                // Console.WriteLine("this");

                openDatabase();
                double power = Program.mainFunction(count); //store power in db
                float cpuU = getCurrentCpuUsage();
                storeCpuPower(cpuU, power);
              Console.WriteLine("cpu = " + cpuU);
                Thread.Sleep(3000);
                count++;
                int running = DisplayProcessStatus(workbench);
                if (running == 0) { break; }
            }

            //select the last row in taskmanager and get dataid

           cmd = new SQLiteCommand("  SELECT taskmanager.dataid FROM taskManager ", sql_con);

       
            queryCommandReader = cmd.ExecuteReader();
          
                openDatabase();
               
                dataTable = new DataTable();
               
                dataTable.Load(queryCommandReader);
                int check = dataTable.Rows.Count;
                
                int rn = dataTable.Rows.Count - 1;
                int id = (int) dataTable.Rows[rn][0];

            matrixR m1 = storeInMatrix(id);
            string modelname = Interaction.InputBox("Please enter the model of laptop.\n\nEg: Fujitsu-S7211", "Model Name Required", "insert here");
            Regression1.regression.regressioncontrol(m1.numberOfRows, m1.matrix1, modelname);


            Console.WriteLine("wait");


        }
    }
}